package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.ReadBehaviorDto;
import com.heima.behavior.entity.ApReadBehavior;
import com.heima.behavior.mapper.ApReadBehaviorMapper;
import com.heima.behavior.service.IApReadBehaviorService;
import com.heima.common.dto.ResponseResult;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP阅读行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-18
 */
@Service
public class ApReadBehaviorServiceImpl extends ServiceImpl<ApReadBehaviorMapper, ApReadBehavior> implements IApReadBehaviorService {

    /**
     * 保存阅读文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveRead(ReadBehaviorDto dto) {

        LambdaQueryWrapper<ApReadBehavior> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(ApReadBehavior::getArticleId,dto.getArticleId());

        ApReadBehavior one = this.getOne(wrapper);

        if (one==null) {
            ApReadBehavior readBehavior = new ApReadBehavior();

            readBehavior.setEntryId(dto.getUserId());
            readBehavior.setArticleId(Long.valueOf(dto.getArticleId()));

            readBehavior.setCount(dto.getCount());
            readBehavior.setReadDuration(dto.getReadDuration());
            readBehavior.setPercentage(dto.getPercentage());
            readBehavior.setLoadDuration(dto.getLoadDuration());
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());

            this.save(readBehavior);
        }else {

            LambdaUpdateWrapper<ApReadBehavior> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ApReadBehavior::getArticleId,one.getArticleId());
            updateWrapper.set(ApReadBehavior::getUpdatedTime,new Date());
            updateWrapper.set(ApReadBehavior::getCount,dto.getCount());
            updateWrapper.set(ApReadBehavior::getReadDuration,dto.getReadDuration());
            updateWrapper.set(ApReadBehavior::getPercentage,dto.getPercentage());
            updateWrapper.set(ApReadBehavior::getLoadDuration,dto.getLoadDuration());
            this.update(wrapper);

        }

        return ResponseResult.okResult();
    }
}
